import React from 'react';
import { connect } from 'react-redux';
import BaseComponent from '../../components/common/baseComponent.js';
import Button from '../../components/common/button';
import CouponSelectModal from '../../components/coupon/couponSelectModal';
// import { getQueryParam } from '../../utils/url';
import CouponCell from '../../components/coupon/couponCell';
import toast from '../../utils/toast';
import { debounced } from '../../utils/func';
import wechatIcon from '../../../assets/images/pay/wechat.png';
import vipIcon from '../../../assets/images/pay/vip.png';
import vipSilverIcon from '../../../assets/images/pay/vip_silver.png';

@connect(({
  coupon,
  loading,
  pay,
  vip,
}) => {
  const couponList = coupon.get('payCouponList');
  const vipList = vip.getIn(['vip', 'list']);
  const selectedVip = vipList.getIn([0, 'selected']) === true;
  const showCoupon = couponList.size > 0 && !selectedVip;
  return {
    showCoupon,
    vipList,
    selectedVip,
    couponList,
    maxSelect: coupon.get('maxSelect'),
    disabled: ['user/fetchUserVip', 'coupon/fetchAndCalPayCoupon', 'coupon/fetchAndCalPayCouponWithoutSelect'].some(action => loading.effects[action]),
    loading: ['refuel/refuel', 'pay/prePay', 'pay/doPay'].some(action => loading.effects[action]),
    money: pay.get('money'),
  };
})
class Pay extends BaseComponent {
  state = {
    order: (this.props.location.state || {}).order,
    selectWechat: true,
  }
  componentDidMount() {
    const { order } = this.state;
    if (!order) {
      this.props.history.goBack();
    }
    this.props.dispatch({
      type: 'vip/fetchUserVip',
    });
    this.props.dispatch({
      type: 'coupon/fetchAndCalPayCouponWithoutSelect',
      payload: {
        listParams: {
          mchId: order.mchId,
          source: window.source,
        },
        calParams: {
          amount: order.orderAmount,
          mchId: order.mchId,
          ownSelectIds: [],
          source: window.source,
        },
      },
    });
  }

  componentWillReceiveProps(nextProps) {
    const { vipList, couponList } = nextProps;
    if (vipList !== this.props.vipList || couponList !== this.props.couponList) {
      this.calMoney();
    }
  }

  calMoney = debounced(() => {
    const { showCoupon, couponList, vipList } = this.props;
    const { order } = this.state;
    const couponIdList = showCoupon ? couponList.filter(coupon => coupon.get('selected')).map(coupon => coupon.get('id')).toJS() : [];
    this.props.dispatch({
      type: 'pay/calPayMoney',
      payload: {
        equityIdList: vipList.filter(vip => vip.get('selected')).map(vip => vip.get('id')).toJS(),
        couponIdList,
        orderNo: order.orderNo,
      },
    });
  }, 500);

  clickPay = debounced(() => {
    console.log('click pay');
    const { selectWechat } = this.state;

    if (!selectWechat) {
      toast('请选择支付方式');
    } else {
      this.doPay();
    }
  }, 300)


  doPay = () => {
    const { order } = this.state;
    const { couponList, showCoupon, vipList } = this.props;
    const couponIdList = showCoupon ? couponList.filter(coupon => coupon.get('selected')).map(coupon => coupon.get('id')).toJS() : [];

    this.props.dispatch({
      type: 'pay/prePay',
      payload: {
        type: 'QIJI_REFUEL',
        payModes: [2],
        payMode: 'WECHATPUBLIC',
        couponIdList,
        equityIdList: vipList.filter(vip => vip.get('selected')).map(vip => vip.get('id')).toJS(),
        orderType: 1,
        payOrderNo: order.orderNo,
        callBackUrl: `${window.location.href.split('#')[0]}#/qiji/result?type=order&&orderNo=${order.orderNo}`,
      },
    });
  }

  showCouponModal = () => {
    this.props.dispatch({
      type: 'coupon/sortCouponList',
    });
    this.modal.show();
  }

  selectCoupon = (coupon) => {
    const { order } = this.state;
    this.props.dispatch({
      type: 'coupon/selectRefuelCoupon',
      payload: {
        selectCoupon: coupon,
        number: order.orderAmountYuan,
      },
    });
  }

  selectCouponDone = () => {
    this.modal.close();
  }

  selectWechat = () => {
    this.setState({ selectWechat: !this.state.selectWechat });
  }

  selectVip = () => {
    this.props.dispatch({
      type: 'vip/selectVip',
    });
  }

  render() {
    const {
      couponList,
      maxSelect,
      loading,
      disabled,
      vipList,
      showCoupon,
      money,
    } = this.props;

    const { order, selectWechat } = this.state;
    if (!order) {
      return null;
    }

    let vipView;
    if (vipList.size > 0) {
      const vip = vipList.first();
      vipView = (
        <div className="pay-cell" onClick={this.selectVip}>
          <img src={vip.get('cardId') === 1 ? vipIcon : vipSilverIcon} alt="" className="icon" />
          <div className="title">{vip.get('cardName')}(加油每升立减{vip.get('amountYuan')}元)</div>
          <i className={`iconfont icon-checkbox ${vip.get('selected') ? 'icon-checked' : 'icon-unchecked'}`} />
        </div>
      );
    }

    let couponView;
    const selectedCouponList = couponList.filter(coupon => coupon.get('selected'));
    if (showCoupon) {
      const couponCells = selectedCouponList.map((coupon, index) => {
        return <CouponCell coupon={coupon} key={index} />;
      });
      couponView = (
        <div className="coupon-view" onClick={this.showCouponModal}>
          <div className="title-row">
            <div className="title">加油优惠券</div>
            <p className="text">已选择<span className="num">{selectedCouponList.size}</span>张</p>
            <i className="iconfont icon-arrow" />
          </div>
          {couponCells}
        </div>
      );
    }

    let disView;
    if (money) {
      if (Number(money.get('couponAmountYuan')) > 0) {
        disView = <p className="dis">优惠券抵扣{money.get('couponAmountYuan')}元</p>;
      } else if (Number(money.get('equityAmountYuan')) > 0) {
        disView = <p className="dis">会员权益抵扣{money.get('equityAmountYuan')}元</p>;
      }
    }

    return (
      <div className="pay">
        <div className="content">
          <div className="order-info-view">
            <div className="title">订单金额</div>
            <div className="money-row"><div className="unit">&#65509;</div><div className="money">{order.orderAmountYuan}</div></div>
            {disView}
          </div>
          <div className="pay-view">
            <div className="pay-cell" onClick={this.selectWechat}>
              <img src={wechatIcon} alt="" className="icon" />
              <div className="title">微信支付</div>
              <i className={`iconfont icon-checkbox ${selectWechat ? 'icon-checked' : 'icon-unchecked'}`} />
            </div>
            {vipView}
          </div>
          {couponView}
        </div>
        <Button title="立即支付" className="pay-btn" clickFunc={this.clickPay} loading={loading} disabled={disabled} />
        <CouponSelectModal
          ref={modal => this.modal = modal}
          couponList={couponList}
          selectFunc={this.selectCoupon}
          confirmFunc={this.selectCouponDone}
          maxSelect={maxSelect}
        />
      </div>
    );
  }
}

export default Pay;
